<template>
  <div class="address-edit">
    <!-- 面包屑 -->
    <section class="breadcrumb">
      <div class="container">
        <router-link to="/">首页</router-link>
        <span>/</span>
        <router-link to="/user-center">个人中心</router-link>
        <span>/</span>
        <router-link to="/addresslist">地址管理</router-link>
        <span>/</span>
        <span>修改收货地址</span>
      </div>
    </section>

    <!-- 主体 -->
    <main class="container">
      <div class="address-edit-header">
        <h1>修改收货地址</h1>
        <router-link to="/addresslist" class="back-btn">
          <i class="fa fa-arrow-left"></i> 返回列表
        </router-link>
      </div>

      <!-- 地址编辑表单 -->
      <div class="edit-form-card">
        <form @submit.prevent="handleSubmit" class="address-form">
          <div class="form-group">
            <label for="recipientName" class="form-label">收货人</label>
            <input
              type="text"
              id="recipientName"
              v-model="form.name"
              class="form-input"
              placeholder="请输入收货人姓名"
              required
            >
          </div>

          <div class="form-group">
            <label for="phone" class="form-label">手机号码</label>
            <input
              type="tel"
              id="phone"
              v-model="form.phone"
              class="form-input"
              placeholder="请输入手机号码"
              pattern="^1[3-9]\d{9}$"
              required
            >
            <p class="error-tip" v-if="phoneError">{{ phoneError }}</p>
          </div>

          <!-- 地址选择区域 -->
          <div class="form-group address-select-group">
            <label class="form-label">所在地区</label>
            <div class="address-selector">
              <select
                v-model="form.province"
                class="form-select"
                @change="handleRegionChange"
                required
              >
                <option value="">请选择省份</option>
                <option v-for="province in provinces" :key="province.code" :value="province.name">
                  {{ province.name }}
                </option>
              </select>
              <select
                v-model="form.city"
                class="form-select"
                @change="handleRegionChange"
                :disabled="!form.province"
                required
              >
                <option value="">请选择城市</option>
                <option v-for="city in cities" :key="city.code" :value="city.name">
                  {{ city.name }}
                </option>
              </select>
              <select
                v-model="form.county"
                class="form-select"
                :disabled="!form.city"
                required
              >
                <option value="">请选择区县</option>
                <option v-for="county in counties" :key="county.code" :value="county.name">
                  {{ county.name }}
                </option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label for="detailAddress" class="form-label">详细地址</label>
            <textarea
              id="detailAddress"
              v-model="form.detail"
              class="form-textarea"
              placeholder="请输入详细地址（街道、门牌号等）"
              rows="3"
              required
            ></textarea>
          </div>

          <div class="form-group">
            <label class="form-checkbox-label">
              <input
                type="checkbox"
                v-model="form.isDefault"
                class="form-checkbox"
              >
              <span>设为默认收货地址</span>
            </label>
          </div>

          <div class="form-actions">
            <button type="button" class="cancel-btn" @click="$router.push('/addresslist')">
              取消
            </button>
            <button type="submit" class="save-btn">
              <i class="fa fa-save"></i> 保存修改
            </button>
          </div>
        </form>
      </div>
    </main>

    <!-- 底部 -->
    <Footer />

    <!-- 返回顶部 -->
    <transition name="fade">
      <button class="back-top" v-show="showTop" @click="toTop">
        <i class="fa fa-arrow-up"></i>
      </button>
    </transition>

    <!-- 成功提示 -->
    <transition name="toast">
      <div v-if="toastOpen" class="toast">
        <i class="fa fa-check-circle"></i>
        <span>{{ toastMsg }}</span>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: "EditAddress",
  computed: {
    userProfile() {
      return this.$store.state.profile;
    }
  },
  data() {
    return {
      showTop: false,
      toastOpen: false,
      toastMsg: "",
      phoneError: "",
      // 地址表单数据
      form: {
        id: null,
        name: "",
        phone: "",
        province: "",
        city: "",
        county: "",
        detail: "",
        isDefault: false
      },
      // 省份数据（实际项目中建议从接口获取）
      provinces: [
        { code: "310000", name: "上海市" },
        { code: "110000", name: "北京市" },
        { code: "440000", name: "广东省" },
        { code: "330000", name: "浙江省" },
        { code: "320000", name: "江苏省" }
      ],
      // 城市数据（实际项目中建议从接口获取）
      cities: [],
      // 区县数据（实际项目中建议从接口获取）
      counties: []
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
    // 获取地址ID并加载地址详情
    const addressId = this.$route.query.id;
    console.log("获取到的地址ID：", addressId)
    if (addressId) {
      this.form.id = addressId;
      console.log('addressId'+addressId)
      console.log('form_id'+this.form.id)
      this.getAddressDetail(this.form.id);
    } else {
      // 没有地址ID时跳回地址列表
      this.$router.push("/editaddress");
      this.showToast("地址ID不存在");
    }
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    // 处理滚动事件
    handleScroll() {
      this.showTop = window.scrollY > 300;
    },
    // 返回顶部
    toTop() {
      window.scrollTo({ top: 0, behavior: "smooth" });
    },
    // 显示提示消息
    showToast(msg) {
      this.toastMsg = msg;
      this.toastOpen = true;
      setTimeout(() => {
        this.toastOpen = false;
      }, 3000);
    },
    // 获取地址详情
    getAddressDetail(addressId) {
      this.$axios.get(`http://127.0.0.1:8000/userAddress/one/${addressId}`)
        .then(res => {
          const address = res.data
          // 解析地址数据到表单
          this.form = {
            id: address.id,
            name: address.recipient_name,
            phone: address.phone,
            province: address.province,
            city: address.city,
            county: address.county,
            detail: address.detail_address,
            isDefault: address.is_default
          };
          console.log(this.form.id)
          console.log(this.form.name)
          // 加载对应城市和区县数据
          this.loadCities(address.province);
          this.loadCounties(address.city);
        })
        .catch(err => {
          console.error("加载地址详情失败", err);
          this.showToast("加载地址详情失败");
          this.$router.push("/editaddress");
        });
    },
    // 加载城市数据（实际项目中建议从接口获取）
    loadCities(provinceName) {
      // 模拟城市数据，实际项目中应根据省份ID从接口获取
      const cityMap = {
        "上海市": [{ code: "310100", name: "上海市" }],
        "北京市": [{ code: "110100", name: "北京市" }],
        "广东省": [
          { code: "440100", name: "广州市" },
          { code: "440300", name: "深圳市" },
          { code: "440600", name: "佛山市" }
        ],
        "浙江省": [
          { code: "330100", name: "杭州市" },
          { code: "330200", name: "宁波市" },
          { code: "330300", name: "温州市" }
        ],
        "江苏省": [
          { code: "320100", name: "南京市" },
          { code: "320500", name: "苏州市" },
          { code: "320200", name: "无锡市" }
        ]
      };
      this.cities = cityMap[provinceName] || [];
      // 重置区县数据
      this.counties = [];
      this.form.city = "";
      this.form.county = "";
    },
    // 加载区县数据（实际项目中建议从接口获取）
    loadCounties(cityName) {
      // 模拟区县数据，实际项目中应根据城市ID从接口获取
      const countyMap = {
        "上海市": [
          { code: "310101", name: "黄浦区" },
          { code: "310115", name: "浦东新区" },
          { code: "310104", name: "徐汇区" }
        ],
        "北京市": [
          { code: "110101", name: "东城区" },
          { code: "110105", name: "朝阳区" },
          { code: "110108", name: "海淀区" }
        ],
        "广州市": [
          { code: "440106", name: "天河区" },
          { code: "440104", name: "越秀区" },
          { code: "440111", name: "白云区" }
        ],
        "深圳市": [
          { code: "440304", name: "福田区" },
          { code: "440305", name: "南山区" },
          { code: "440306", name: "宝安区" }
        ]
      };
      this.counties = countyMap[cityName] || [];
      this.form.county = "";
    },
    // 地区选择变化处理
    handleRegionChange() {
      if (this.form.province) {
        this.loadCities(this.form.province);
      }
      if (this.form.city) {
        this.loadCounties(this.form.city);
      }
    },
    // 验证手机号
    validatePhone() {
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!this.form.phone) {
        this.phoneError = "请输入手机号码";
        return false;
      } else if (!phoneReg.test(this.form.phone)) {
        this.phoneError = "请输入正确的手机号码";
        return false;
      } else {
        this.phoneError = "";
        return true;
      }
    },
    // 提交表单
    handleSubmit() {
      // 验证手机号
      if (!this.validatePhone()) return;

      // 准备提交数据
      const submitData = {
        recipient_name: this.form.name,
        phone: this.form.phone,
        province: this.form.province,
        city: this.form.city,
        county: this.form.county,
        detail_address: this.form.detail,
        is_default: this.form.isDefault,
        user_id: this.userProfile?.id
      };

      // 调用接口更新地址
      this.$axios.put(`http://127.0.0.1:8000/userAddress/${this.form.id}`, submitData)
        .then(res => {
          this.showToast("地址修改成功");
          // 延迟跳转回地址列表
          setTimeout(() => {
            this.$router.push("/addresslist");
          }, 1500);
        })
        .catch(err => {
          console.error("修改地址失败", err);
          this.showToast("修改地址失败，请重试");
        });
    }
  }
};
</script>

<style scoped>
/* 全局变量（与AddressList保持一致） */
:root {
  --primary: #8b5a2b;
  --secondary: #d2b48c;
  --accent: #cd853f;
  --light: #f5f5dc;
  --dark: #3e2723;
  --radius: 12px;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  --error: #e53e3e;
}
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

/* 面包屑（复用AddressList样式） */
.breadcrumb {
  background: #fff;
  border-bottom: 1px solid #eee;
  padding: 12px 0;
  font-size: 14px;
  color: #666;
}
.breadcrumb a {
  color: var(--primary);
}
.breadcrumb span {
  margin: 0 6px;
}

/* 主体区域 */
main {
  padding: 40px 0;
}
.address-edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}
.address-edit-header h1 {
  font-size: 28px;
  font-weight: 700;
}
.back-btn {
  color: var(--primary);
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
}
.back-btn:hover {
  text-decoration: underline;
}

/* 表单卡片 */
.edit-form-card {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 32px;
  max-width: 800px;
  margin: 0 auto;
}

/* 表单样式 */
.address-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.form-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}
.form-input,
.form-select,
.form-textarea {
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}
.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(139, 90, 43, 0.1);
}
.form-textarea {
  resize: vertical;
}

/* 地址选择器 */
.address-select-group {
  gap: 12px;
}
.address-selector {
  display: flex;
  gap: 12px;
}
.form-select {
  flex: 1;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%23333' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 12px center;
  background-size: 16px;
}

/* 复选框样式 */
.form-checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}
.form-checkbox {
  width: 16px;
  height: 16px;
  accent-color: var(--primary);
}

/* 错误提示 */
.error-tip {
  margin: 0;
  font-size: 12px;
  color: var(--error);
  margin-top: 4px;
}

/* 表单操作按钮 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 16px;
}
.cancel-btn,
.save-btn {
  padding: 10px 24px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}
.cancel-btn {
  background: #fff;
  border: 1px solid #ddd;
  color: #666;
}
.cancel-btn:hover {
  border-color: #ccc;
  background: #f9f9f9;
}
.save-btn {
  background: var(--primary);
  border: none;
  color: #fff;
  display: flex;
  align-items: center;
  gap: 6px;
}
.save-btn:hover {
  background: var(--dark);
}

/* 底部（复用AddressList样式） */
.site-footer {
  margin-top: 80px;
  background: var(--dark);
  color: #fff;
  padding: 48px 24px 24px;
}
.footer-inner {
  max-width: 1200px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 40px;
}
.footer-brand {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 22px;
  font-weight: 700;
  margin-bottom: 12px;
}
.footer-brand i {
  color: var(--secondary);
}
.footer-social {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}
.footer-social a {
  width: 36px;
  height: 36px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  display: grid;
  place-items: center;
  transition: background 0.3s;
}
.footer-social a:hover {
  background: rgba(255, 255, 255, 0.2);
}
.footer-col h4 {
  font-size: 18px;
  margin-bottom: 16px;
  font-weight: 600;
}
.footer-col ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
.footer-col li {
  margin-bottom: 8px;
  font-size: 14px;
  color: #ccc;
}
.footer-col li a {
  color: #ccc;
  text-decoration: none;
}
.footer-col li a:hover {
  color: #fff;
}
.footer-bottom {
  text-align: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.2);
  font-size: 14px;
  color: #aaa;
}

/* 返回顶部（复用AddressList样式） */
.back-top {
  position: fixed;
  right: 24px;
  bottom: 24px;
  width: 48px;
  height: 48px;
  background: var(--primary);
  color: #fff;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  z-index: 999;
  display: grid;
  place-items: center;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 提示框（复用AddressList样式） */
.toast {
  position: fixed;
  top: 100px;
  right: 24px;
  background: #38a169;
  color: #fff;
  padding: 12px 20px;
  border-radius: var(--radius);
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 60;
}
.toast-enter-active,
.toast-leave-active {
  transition: transform 0.3s;
}
.toast-enter-from,
.toast-leave-to {
  transform: translateX(100%);
}

/* 响应式适配 */
@media (max-width: 768px) {
  .edit-form-card {
    padding: 24px 16px;
  }
  .address-selector {
    flex-direction: column;
    gap: 8px;
  }
  .form-actions {
    flex-direction: column;
  }
  .cancel-btn,
  .save-btn {
    width: 100%;
  }
  .address-edit-header h1 {
    font-size: 24px;
  }
}
</style>